package cy.service.impl;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import org.apache.log4j.Logger;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import cy.dao.UserDaoI;
import cy.model.Tuser;
import cy.pageModel.DataGrid;
import cy.pageModel.User;
import cy.service.UserServiceI;
import cy.util.Encrypt;

@Service("userService")
public class UserServiceImpl implements UserServiceI {
	/**
	 * Logger for this class
	 */
	private static final Logger logger = Logger.getLogger(UserServiceImpl.class);

	private UserDaoI userDao;

	public UserDaoI getUserDao() {
		return userDao;
	}

	@Autowired
	public void setUserDao(UserDaoI userDao) {
		this.userDao = userDao;
	}

	@Override
	public User save(User user) {
		Tuser t = new Tuser();
		user.setPwd(Encrypt.e(user.getPwd()));
		BeanUtils.copyProperties(user, t);
		t.setId(UUID.randomUUID().toString());
		t.setCreattime(new Date());
		userDao.save(t);
		BeanUtils.copyProperties(t, user);
		return user;
	}

	@Override
	public User find(User user) {
		// String hql = "from Tuser t where t.name=? and t.pwd=?";
		// Object[] params = new Object[] { user.getName(),
		// Encrypt.e(user.getPwd()) };
		String hql = "from Tuser t where t.name=:name and t.pwd=:pwd";
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("name", user.getName());
		params.put("pwd", Encrypt.e(user.getPwd()));
		Tuser t = userDao.get(hql, params);
		if (t != null) {
			BeanUtils.copyProperties(t, user);
			return user;
		}
		return null;

	}

	@Override
	public DataGrid dataGrid(User user) {
		String hql = "from Tuser t where 1=1";
		Map<String, Object> params = new HashMap<String, Object>();
		hql = addWhere(user, hql, params);
		String hql_total = "select count(*) " + hql;
		hql = addOrder(user, hql);
		Long count = userDao.count(hql_total, params);
		DataGrid data = new DataGrid();
		List<Tuser> l = userDao.find(hql, params, user.getPage(), user.getRows());
		List<User> nl = new ArrayList<User>();
		changModel(l, nl);
		logger.info(hql + "#######" + user.getStartdate() + user.getEnddate());
		data.setTotal(count);
		data.setRows(nl);
		return data;
	}

	private void changModel(List<Tuser> l, List<User> nl) {
		if (l != null && l.size() > 0) {
			for (Tuser o : l) {
				User u = new User();
				BeanUtils.copyProperties(o, u);
				nl.add(u);
			}
		}
	}

	private String addOrder(User user, String hql) {
		if (user.getSort() != null && user.getOrder() != null) {
			hql += "order by " + user.getSort() + " " + user.getOrder();
		}
		return hql;
	}

	private String addWhere(User user, String hql, Map<String, Object> params) {
		if (user.getName() != null && !user.getName().trim().equals("")) {
			hql += " and t.name like :name ";
			params.put("name", "%" + user.getName() + "%");
		}
		if (user.getStartdate() != null && !"".equals(user.getStartdate()) && user.getEnddate() != null && !"".equals(user.getEnddate())) {
			SimpleDateFormat sipfor=new SimpleDateFormat("yyyy-MM-dd");
			hql += " and creattime between '"+sipfor.format(user.getStartdate())+"' and '"+sipfor.format(user.getEnddate())+"' ";
			//params.put("startdate", user.getStartdate());
			//params.put("enddate", user.getEnddate());
		}
		return hql;
	}

	@Override
	public int delete(User user) {
		String hql = "delete from Tuser where id in (";
		String[] ids = user.getIds().split(",");
		if (ids.length > 0) {
			for (int i = 0; i < ids.length; i++) {
				if (i == 0) {
					hql += "'" + ids[i] + "'";
				}
				else {
					hql += ",'" + ids[i] + "'";
				}
			}
		}
		hql += ")";
		logger.info(hql);
		return userDao.excuteHql(hql);
	}

	@Override
	public User edit(User user) {
		Tuser t = userDao.get(Tuser.class, user.getId());
		user.setModifytime(new Date());
		BeanUtils.copyProperties(user, t, new String[] { "id", "pwd", "creattime" });
		return user;
	}

}
